var timerId = "";

var oWCSelectedMatches;
var oWCSelectedLiveMatches;

var bIsAnyMatch = false;
var bInitSchedule = true;

var strUrlFacebook = "";
var strUrlTwitter = "";
var strUrlBuzz = "";

var strTextIcon = "";

var strDebug = "";

var strAlertFollowingMatch = '<div class="content-gce-fifa-wc"><span class="feed-gce-fifa-wc">{0}</span><div class="teams-gce-fifa-wc"><span class="team1-gce-fifa-wc"><a target="_blank" href="{8}"><img src="{1}"/>&nbsp;{2}</span> <font color="#000000">{3}</font> <span class="team2-gce-fifa-wc">{4}&nbsp;<img src="{5}" /></a></span></div><div class="share-gce-fifa-wc">{6}:<br/>{7}</div></div>';


var strShare = "<a href='#' onclick='shareFacebook(\"{0}\",\"{1}\");'><img src=&#039;http://gce-fifa-worldcup.googlecode.com/svn/trunk/gce-fifa-worldcup/img/ico-facebook.gif&#039; alt=&#039;&#039; /></a><a href='#' onclick='shareTwitter(\"{0}\",\"{1}\");'><img style=\"cursor:pointer\" src=&#039;http://gce-fifa-worldcup.googlecode.com/svn/trunk/gce-fifa-worldcup/img/ico-twitter.gif&#039; alt=&#039;&#039; /></a><a href='#' onclick='shareBuzz(\"{0}\",\"{1}\");'><img src=&#039;http://gce-fifa-worldcup.googlecode.com/svn/trunk/gce-fifa-worldcup/img/ico-googlewave.gif&#039; alt=&#039;&#039; /></a>";


function refreshExtension(){	   
//	getMatches();
    getLiveMatches();
}

function init(){
    !localStorage.getObject('wcSelectedMatches') ? oWCSelectedMatches = {} : oWCSelectedMatches = localStorage.getObject('wcSelectedMatches');
    
    // Conditionally initialize the options.
    if (!localStorage.isInitialized) {
        localStorage.isActivated = true; // The display activation.
        localStorage.frequency = 1; // The display frequency, in minutes.
        localStorage.isInitialized = true; // The option initialization.
        // go to Options Page 
        chrome.tabs.getAllInWindow(null, function(tabs){
            var bReturn = false;
            var strOptionsPage = "chrome-extension://" + chrome.i18n.getMessage("@@extension_id") + "/view/options.html";
            tabs.forEach(function(tab){
                if (tab.url == strOptionsPage) {
                    bReturn = true;
                }
            });
            if (!bReturn) {
                chrome.tabs.create({
                    url: "view/options.html"
                });
            }
        });
        
    }
    
	
    // Test for notification support.
    if (webkitNotifications) {
        // While activated, show notifications at the display frequency.
        if (JSON.parse(localStorage.isActivated)) {
            refreshExtension();
        }
        
		var dateFinishWC = new Date();
		var dateToday = new Date();
		dateFinishWC.setFullYear(2010, 6, 12);
		if (dateToday < dateFinishWC)
		{
	        var interval = 0; // The display interval, in minutes.
	        setInterval(function(){
	            interval++;
	            
	            if (JSON.parse(localStorage.isActivated) &&
	            localStorage.frequency <= interval) {
	                refreshExtension();
	                interval = 0;
	            }
	        }, 90000);			
		}
    }
}


function getFacebook(strUrl, strTitle){
    return String.format(share_facebook, URLEncode(strUrl), URLEncode(strTitle));
}

function getBuzz(strUrl, strTitle){
    return String.format(share_buzz, URLEncode(strUrl), URLEncode(strTitle))
}

function getTwitter(strUrl, strTitle){
    return String.format(share_twitter, URLEncode(strTitle) + " " + encodeURIComponent(strUrl))    
}

function startRequest(){
    getLiveMatches();
    scheduleRequest();
}


function scheduleRequest(){
	var dateFinishWC = new Date();
	var dateToday = new Date();
	dateFinishWC.setFullYear(2010, 6, 12);
	if (dateToday < dateFinishWC) {
		if (timerId != "") {
			window.clearTimeout(timerId);
		}
		var delay = 10 * 60 * 1000; // 10 minutes
		if (bInitSchedule) {
			delay = 20 * 1000; // 10 seconds
			bInitSchedule = false;
		}
		else 
			if (bIsAnyMatch) 
				delay = 60 * 1000; // 1 minute
			else 
				delay = 2 * 60 * 1000; // 2 minutes  
		timerId = window.setTimeout(startRequest, delay);
	}
}


function getMatches(){
    try {
        // Init my_team
        if (!localStorage['my_team']) {
            localStorage.setItem('my_team', '---|---|---');
        }
        
        localStorage.removeItem('my_team_group_name');
        
        var strTeamUrl = "";
        
        if (!bWCDebug) 
            strTeamUrl = getUI('main_url_feed_2') + feed_matches;
        else 
            strTeamUrl = feed_matches_debug;
        
        var xhr = new XMLHttpRequest();
        xhr.open("GET", strTeamUrl + "?t=" + getCacheNumber(), false);
        
        xhr.onreadystatechange = function(){
            if (xhr.readyState == 4) {
                var json = "";
                
                try {
                    xmlString = xhr.responseXML.xml ? xhr.responseXML.xml : (new XMLSerializer()).serializeToString(xhr.responseXML);
                } 
                catch (e) {
                    xmlString = xhr.responseText;
                }
                
                json = $.xml2json(xmlString);
                
                
                if (json != "") {
                    oWCMatches = json;
                    var strNew = "";
                    oWCStages = new Array();
                    oWCGroups = new Array();
                    var j = 0;
                    var k = 0;
                    var strIdTab = "";
                    var strIdStage = "";
                    var strIdGroup = "";
                    // Find Group of My Team
                    for (var i = 0; i < oWCMatches.Data.Match.length; i++) {
                        if ((localStorage['my_team'].split("|")[1] == oWCMatches.Data.Match[i].Team[0].ShortName) || (localStorage['my_team'].split("|")[1] == oWCMatches.Data.Match[i].Team[1].ShortName)) {
                            if (oWCMatches.Data.Match[i].Group.code.length > 0) {
                                localStorage.setItem('my_team_group_id', oWCMatches.Data.Match[i].Group.code);
                                localStorage.setItem('my_team_group_name', oWCMatches.Data.Match[i].Group.text);
                            }
                        }
                    }
                    // Init Fields
                    for (var i = 0; i < oWCMatches.Data.Match.length; i++) {
                        if (localStorage['follow_my_team'] == 1) {
                            if ((localStorage['my_team'].split("|")[1] == oWCMatches.Data.Match[i].Team[0].ShortName) || (localStorage['my_team'].split("|")[1] == oWCMatches.Data.Match[i].Team[1].ShortName)) {
                                oWCSelectedMatches[oWCMatches.Data.Match[i].code] = 1;
                            }
                        }
                        
                        if (localStorage['follow_my_group_teams'] == 1) {
                            if (oWCMatches.Data.Match[i].Group.code.length > 0) {
                                if (oWCMatches.Data.Match[i].Group.code == localStorage['my_team_group_id']) {
                                    oWCSelectedMatches[oWCMatches.Data.Match[i].code] = 1;
                                }
                            }
                        }
                        
                        if (localStorage['follow_all_teams'] == 1) {
                            oWCSelectedMatches[oWCMatches.Data.Match[i].code] = 1;
                        }
                        
                        
                    }
                    
                    localStorage.setObject("wcSelectedMatches", oWCSelectedMatches);
                    
                }
            }
        }
        xhr.send();
    } 
    catch (e) {
    
    }
}

function getLiveMatches(){
    !localStorage.getObject('wcSelectedMatches') ? oWCSelectedMatches = {} : oWCSelectedMatches = localStorage.getObject('wcSelectedMatches');
    !localStorage.getObject('wcSelectedLiveMatches') ? oWCSelectedLiveMatches = {} : oWCSelectedLiveMatches = localStorage.getObject('wcSelectedLiveMatches');
    
    try {
        var strTeamUrl = "";
        
        if (!bWCDebug) 
            strTeamUrl = getUI('main_url_feed_2') + feed_matches;
        else 
            strTeamUrl = feed_matches_debug;
        
        var xhr = new XMLHttpRequest();
        xhr.open("GET", strTeamUrl + "?t=" + getCacheNumber(), false);
        xhr.onreadystatechange = function(){
            if (xhr.readyState == 4) {
                var json = "";
                
                try {
                    xmlString = xhr.responseXML.xml ? xhr.responseXML.xml : (new XMLSerializer()).serializeToString(xhr.responseXML);
                } 
                catch (e) {
                    xmlString = xhr.responseText;
                }
                
                json = $.xml2json(xmlString);
                
                bIsAnyMatch = false;
                setIconText("");
                if (json != "") {
                    oWCMatches = json;
                    // Find Group of My Team
                    for (var i = 0; i < oWCMatches.Data.Match.length; i++) {
                        if (oWCMatches.Data.Match[i].Status.code == "3") {
                            if (oWCSelectedMatches[oWCMatches.Data.Match[i].code] == 1) {
                                if (oWCSelectedLiveMatches[oWCMatches.Data.Match[i].code] == undefined) {
                                    oWCSelectedLiveMatches[oWCMatches.Data.Match[i].code] = 0;
									if (!localStorage[oWCMatches.Data.Match[i].ShortName]) {										
										trackEvent("LiveMatch", oWCMatches.Data.Match[i].ShortName);
										localStorage[oWCMatches.Data.Match[i].ShortName] = "1";
									}									
                                    showFollowingMatch(String.format(flag_pattern_s, oWCMatches.Data.Match[i].Team[0].ShortName), oWCMatches.Data.Match[i].Team[0].ShortName, oWCMatches.Data.Match[i].Result.Live.H, oWCMatches.Data.Match[i].Result.Live.A, oWCMatches.Data.Match[i].Team[1].ShortName, String.format(flag_pattern_s, oWCMatches.Data.Match[i].Team[1].ShortName), oWCMatches.Data.Match[i].OfficialSiteLink);
                                    bIsAnyMatch = true;
                                }
                                else {
                                    bIsAnyMatch = true;
                                    getLiveMatch(oWCMatches.Data.Match[i].code);
                                }
                            }
                        }
                    }
                    localStorage.setObject("wcSelectedLiveMatches", oWCSelectedLiveMatches);
                }
            }
        }
        xhr.send();
    } 
    catch (ex) {
    
    }
    
    
}

function getLiveMatch(strMatchCode){
    var strTeamUrl = "";
    
    if (!bWCDebug) 
        strTeamUrl = getUI('main_url_feed_2') + String.format(feed_live_match, strMatchCode);
    else 
        strTeamUrl = String.format(feed_live_match_debug, strMatchCode);
		
    var xhr = new XMLHttpRequest();
    xhr.open("GET", strTeamUrl + "?t=" + getCacheNumber(), false);
    xhr.onreadystatechange = function(){
        if (xhr.readyState == 4) {
            var xmlString = "";
            
            var json = "";
            try {
                xmlString = xhr.responseXML.xml ? xhr.responseXML.xml : (new XMLSerializer()).serializeToString(xhr.responseXML);
            } 
            catch (e) {
                xmlString = xhr.responseText;
            }
            json = $.xml2json(xmlString);
            if (json != "") {
                oWCLiveMatch = json;
                // only show the selected events (goals and start/stop)
                var i, j;
                if (oWCSelectedLiveMatches[oWCLiveMatch.Data.Match.code] != undefined) 
                    j = oWCSelectedLiveMatches[oWCLiveMatch.Data.Match.code];
                else 
                    j = 0;
                if (oWCLiveMatch.Data.Match.Actions.Action.length == undefined) {
                    i = 0;
                    if (oWCLiveMatch.Data.Match.Actions.Action.Kind.code in match_live_events) {
                        var strTime = "";
                        var strPlayer = "";
                        var strTeam = "";
                        oWCLiveMatch.Data.Match.Actions.Action.Time.text == undefined ? strTime = "" : strTime = oWCLiveMatch.Data.Match.Actions.Action.Time.text;
                        oWCLiveMatch.Data.Match.Actions.Action.Player.text == undefined ? strPlayer = "" : strPlayer = oWCLiveMatch.Data.Match.Actions.Action.Player.text;
                        oWCLiveMatch.Data.Match.Actions.Action.Team.text == undefined ? strTeam = "" : strTeam = oWCLiveMatch.Data.Match.Actions.Action.Team.text;
                        var strShareText = "";
						var strShareTextWeb = "";
						strShareText = strTime + " " + oWCLiveMatch.Data.Match.Actions.Action.Period.text + " (" + oWCLiveMatch.Data.Match.Actions.Action.Kind.text + ")";     
						strShareTextWeb = "[#" + oWCLiveMatch.Data.Match.Team[0].ShortName + " " + oWCLiveMatch.Data.Match.Result.Live.H + ":" + oWCLiveMatch.Data.Match.Result.Live.A + " #" + oWCLiveMatch.Data.Match.Team[1].FullName + "] " + strTime + " " + oWCLiveMatch.Data.Match.Actions.Action.Kind.text + " " + strPlayer + " (" + oWCLiveMatch.Data.Match.Actions.Action.Period.text + ")";
						
						//strShareText = URLEncode(strShareText);
                        
                        if (oWCSelectedLiveMatches[oWCLiveMatch.Data.Match.code] != i) {;
                            oWCSelectedLiveMatches[oWCLiveMatch.Data.Match.code] = i;
							trackEvent("LiveMatch",oWCLiveMatch.Data.Match.ShortName);
                            showLiveMatch(strShareText, strShareTextWeb, String.format(flag_pattern_s, oWCLiveMatch.Data.Match.Team[0].ShortName), oWCLiveMatch.Data.Match.Team[0].ShortName, oWCLiveMatch.Data.Match.Result.Live.H, oWCLiveMatch.Data.Match.Result.Live.A, oWCLiveMatch.Data.Match.Team[1].ShortName, String.format(flag_pattern_s, oWCLiveMatch.Data.Match.Team[1].ShortName), oWCLiveMatch.Data.Match.OfficialSiteLink);
                        }
                    }
                }
                else 
                    for (var i = j; i < oWCLiveMatch.Data.Match.Actions.Action.length; i++) {
                        if (oWCLiveMatch.Data.Match.Actions.Action[i].Kind.code in match_live_events) {
                            var strTime = "";
                            var strPlayer = "";
                            var strTeam = "";
                            oWCLiveMatch.Data.Match.Actions.Action[i].Time.text == undefined ? strTime = "" : strTime = oWCLiveMatch.Data.Match.Actions.Action[i].Time.text;
                            oWCLiveMatch.Data.Match.Actions.Action[i].Player.text == undefined ? strPlayer = "" : strPlayer = oWCLiveMatch.Data.Match.Actions.Action[i].Player.text;
                            oWCLiveMatch.Data.Match.Actions.Action[i].Team.text == undefined ? strTeam = "" : strTeam = oWCLiveMatch.Data.Match.Actions.Action[i].Team.text;
                            var strShareText = "";
							var strShareTextWeb = "";
							
							strShareText = strTime + " " + oWCLiveMatch.Data.Match.Actions.Action[i].Period.text + "  (" + oWCLiveMatch.Data.Match.Actions.Action[i].Kind.text + ")";
							strShareTextWeb = "[#" + oWCLiveMatch.Data.Match.Team[0].ShortName + " " + oWCLiveMatch.Data.Match.Result.Live.H + ":" + oWCLiveMatch.Data.Match.Result.Live.A + " #" + oWCLiveMatch.Data.Match.Team[1].ShortName + "] " + strTime + " " + oWCLiveMatch.Data.Match.Actions.Action[i].Kind.text + " " + strPlayer + " (" + oWCLiveMatch.Data.Match.Actions.Action[i].Period.text + ")";
                            
                            if (oWCSelectedLiveMatches[oWCLiveMatch.Data.Match.code] != i) {
                                oWCSelectedLiveMatches[oWCLiveMatch.Data.Match.code] = i;
								trackEvent("LiveMatch",oWCLiveMatch.Data.Match.ShortName);								
                                showLiveMatch(strShareText, strShareTextWeb, String.format(flag_pattern_s, oWCLiveMatch.Data.Match.Team[0].ShortName), oWCLiveMatch.Data.Match.Team[0].ShortName, oWCLiveMatch.Data.Match.Result.Live.H, oWCLiveMatch.Data.Match.Result.Live.A, oWCLiveMatch.Data.Match.Team[1].ShortName, String.format(flag_pattern_s, oWCLiveMatch.Data.Match.Team[1].ShortName), oWCLiveMatch.Data.Match.OfficialSiteLink);
                            }
                        }
                    }
                localStorage.setObject("wcSelectedLiveMatches", oWCSelectedLiveMatches);
                setTimeout('$("div .match_live > table").fadeIn();', 150);
            }
        }
    }
    xhr.send();
    
    
}


function showFollowingMatch(strImageA, strTeamA, strResultA, strResultB, strTeamB, strImageB, strMatchLink){
	var strText = getUI("content_txt_you_are_following") + " %23" + strTeamA + " " + strResultA + ":" + strResultB + " %23" + strTeamB;
	
	if (strMatchLink == "") 
		strMatchLink = getUI("main_url");
	
	var strHTML = strAlertFollowingMatch.format(getUI("content_txt_you_are_following"), strImageA, strTeamA, strResultA + ":" + strResultB, strTeamB, strImageB, getUI("content_txt_share_it"), strShare.format(addUrlSuffix(strMatchLink), strText),addUrlSuffix(strMatchLink));
	
	var d = new Date();
	var idMessage = "follow" + d.getTime();
	
	// activate notifications only for LTR languages
	//if (chrome.i18n.getMessage("@@bidi_dir") == "ltr")
	//{ 
	localStorage[idMessage] = strHTML;		
	var notification = webkitNotifications.createHTMLNotification('../view/notification.html?id=' + idMessage);
	notification.show();
	//}
}

function showLiveMatch(strText, strTextWeb, strImageA, strTeamA, strResultA, strResultB, strTeamB, strImageB, strMatchLink){
    
    if (strMatchLink=="")
    	strMatchLink = getUI("main_url");
	else
		strMatchLink = getUI("main_url") + strMatchLink;
				
	var strFacebook = getFacebook(strMatchLink, strTextWeb);
    var strTwitter = getTwitter(strMatchLink, strTextWeb);
    var strBuzz = getBuzz(strMatchLink, strTextWeb);
    
    strTextWeb = strTextWeb.split("'").join("&#039;");
    strTextWeb = URLEncode(strTextWeb);

    var strHTML = strAlertFollowingMatch.format(strText, strImageA, strTeamA, strResultA + ":" + strResultB, strTeamB, strImageB, getUI("content_txt_share_it"), strShare.format(addUrlSuffix(strMatchLink), strTextWeb),addUrlSuffix(strMatchLink));
    
    
	var d = new Date();
	var idMessage = "live" + d.getTime();	
	
	// activate notifications only for LTR languages
	if (chrome.i18n.getMessage("@@bidi_dir") == "ltr") {	
		localStorage[idMessage] = strHTML;
		var notification = webkitNotifications.createHTMLNotification('../view/notification.html?id=' + idMessage);
		notification.show();
	}      
}

// Matches Refresh
chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
    switch (request.getResults) {
        case "initSchedule":
            startRequest();
            sendResponse({}); // snub them.
            break;
            
        case "refreshMatches":
            // Init my_team
            if (!localStorage['my_team']) {
                localStorage.setItem('my_team', '---|---|---');
            }
            
            localStorage.removeItem('my_team_group_name');
            
            var strTeamUrl = "";
            
            
			if (!bWCDebug)
				strTeamUrl = getUI('main_url_feed_2') + feed_matches;
			else
            	strTeamUrl = feed_matches_debug;
            
            var xhr = new XMLHttpRequest();
            xhr.open("GET", strTeamUrl + "?t=" + getCacheNumber(), false);
            
            xhr.onreadystatechange = function(){
                if (xhr.readyState == 4) {
                    var json = "";
                    
                    try {
                        xmlString = xhr.responseXML.xml ? xhr.responseXML.xml : (new XMLSerializer()).serializeToString(xhr.responseXML);
                    } 
                    catch (e) {
                        xmlString = xhr.responseText;
                    }
                    
                    json = $.xml2json(xmlString);
                    
                    
                    if (json != "") {
                        oWCMatches = json;
                        var strNew = "";
                        oWCStages = new Array();
                        oWCGroups = new Array();
                        var j = 0;
                        var k = 0;
                        var strIdTab = "";
                        var strIdStage = "";
                        var strIdGroup = "";
                        // Find Group of My Team
                        for (var i = 0; i < oWCMatches.Data.Match.length; i++) {
                            if ((localStorage['my_team'].split("|")[1] == oWCMatches.Data.Match[i].Team[0].ShortName) || (localStorage['my_team'].split("|")[1] == oWCMatches.Data.Match[i].Team[1].ShortName)) {
                                if (oWCMatches.Data.Match[i].Group.code.length > 0) {
                                    localStorage.setItem('my_team_group_id', oWCMatches.Data.Match[i].Group.code);
                                    localStorage.setItem('my_team_group_name', oWCMatches.Data.Match[i].Group.text);
                                }
                            }
                        }
                        // Init Fields
                        for (var i = 0; i < oWCMatches.Data.Match.length; i++) {
                            if (localStorage['follow_my_team'] == 1) {
                                if ((localStorage['my_team'].split("|")[1] == oWCMatches.Data.Match[i].Team[0].ShortName) || (localStorage['my_team'].split("|")[1] == oWCMatches.Data.Match[i].Team[1].ShortName)) {
                                    oWCSelectedMatches[oWCMatches.Data.Match[i].code] = 1;
                                }
                            }
                            
                            if (localStorage['follow_my_group_teams'] == 1) {
                                if (oWCMatches.Data.Match[i].Group.code.length > 0) {
                                    if (oWCMatches.Data.Match[i].Group.code == localStorage['my_team_group_id']) {
                                        oWCSelectedMatches[oWCMatches.Data.Match[i].code] = 1;
                                    }
                                }
                            }
                            
                            if (localStorage['follow_all_teams'] == 1) {
                                oWCSelectedMatches[oWCMatches.Data.Match[i].code] = 1;
                            }
                            
                        }
                        localStorage.setObject("wcSelectedMatches", oWCSelectedMatches);
                        sendResponse({
                            selectedMatches: JSON.stringify(oWCSelectedMatches)
                        });
                        
                        
                    }
                }
            }
            xhr.send();
            break;
            
        case "playingMatches":
            !localStorage.getObject('wcSelectedLiveMatches') ? oWCSelectedLiveMatches = {} : oWCSelectedLiveMatches = localStorage.getObject('wcSelectedLiveMatches');
            
            
            
            var strTeamUrl = "";
            
            if (!bWCDebug)
				strTeamUrl = getUI('main_url_feed_2') + feed_matches;
			else
            	strTeamUrl = feed_matches_debug;
				
            var xhr = new XMLHttpRequest();
            xhr.open("GET", strTeamUrl + "?t=" + getCacheNumber(), false);
            
            xhr.onreadystatechange = function(){
                if (xhr.readyState == 4) {
                    var json = "";
                    
                    try {
                        xmlString = xhr.responseXML.xml ? xhr.responseXML.xml : (new XMLSerializer()).serializeToString(xhr.responseXML);
                    } 
                    catch (e) {
                        xmlString = xhr.responseText;
                    }
                    
                    json = $.xml2json(xmlString);
                    
                    
                    if (json != "") {
                        oWCMatches = json;
                        // Find Group of My Team
                        for (var i = 0; i < oWCMatches.Data.Match.length; i++) {
                            if (oWCMatched.Data.Match[i].Status.code == "3") {
                                if (oWCSelectedMatches[oWCMatches.Data.Match[i].code] == 1) {
                                    if (oWCSelectedLiveMatches[oWCMatches.Data.Match[i].code] == undefined) {
                                        oWCSelectedLiveMatches[oWCMatches.Data.Match[i].code] = 0;
                                    }
                                }
                            }
                        }
                        localStorage.setObject("wcSelectedLiveMatches", oWCSelectedLiveMatches);
                        sendResponse({
                            selectedLiveMatches: JSON.stringify(oWCSelectedLiveMatches)
                        });
                        
                        
                    }
                }
            }
            xhr.send();
            break;
            
        default:
            sendResponse({}); // snub them.
    }
});

function resetIconAlert(){
    strTextIcon = "";
    setIconText("");
}


function setIconText(strText){
    chrome.browserAction.setBadgeText({
        text: strText
    });
}

Storage.prototype.setObject = function(key, value){
    this.setItem(key, JSON.stringify(value));
}

Storage.prototype.getObject = function(key){
    try {
        return JSON.parse(this.getItem(key));
    } 
    catch (e) {
    }
}
